package com.xzy.shop.service.impl;

import com.xzy.shop.dao.UserDao;
import com.xzy.shop.dao.impl.UserDaoImpl;
import com.xzy.shop.domain.Admin;
import com.xzy.shop.domain.User;
import com.xzy.shop.service.UserService;
import com.xzy.shop.util.MailUtils;
import com.xzy.shop.util.UuidUtil;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    UserDao dao = new UserDaoImpl();
    /**
     * 添加注册用户方法
     * @param user
     * @return
     */
    @Override
    public boolean regist(User user) {
        User u = dao.findByUsername(user.getUsername());
        if (u != null) {
            return false;
        }
        //2.保存用户信息
        //2.1设置激活码，唯一
        user.setCode(UuidUtil.getUuid());
        //2.2设置激活状态
        user.setStatus("N");
        dao.save(user);

        //3.邮件发送，邮件正文
        String content = "<a href='http://localhost:8080/javaweb_shop/user/active?code=" + user.getCode() +"'>点击激活【在线旅游网】</a>";
        MailUtils.sendMail(user.getUsername(), content, "激活邮件");
        return true;
    }

    @Override
    public boolean active(String code) {
        User user = dao.findByCode(code);
        if (user != null) {
            dao.changeStatus(user);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User check(User user) {
        String username = user.getUsername();
        String password = user.getPassword();

        boolean contains = username.contains("@");

        if (contains) {
            return dao.loginByEmail(username, password);
        } else {
            return dao.loginByPhone(username, password);
        }
    }

    @Override
    public boolean checkStatus(User user) {
        String username = user.getUsername();
        User loginuser = dao.findByUsername(username);

        String status = loginuser.getStatus();
        if ("".equals(status) || "N".equalsIgnoreCase(status)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public User addInfo(User user, Map<String, String[]> infos) {
        dao.addInfo(user, infos);

        return dao.findByUsername(user.getUsername());
    }

    @Override
    public Admin adminLogin(String username, String password) {
        return dao.adminLogin(username, password);
    }

    @Override
    public List<User> findAllUser() {
        return dao.findAllUser();
    }
}
